package com.cheyunkeji.er.activity;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cheyun.netsalev3.MyApplication;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
//import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.utils.AsciiCodeLimitFilter;
import com.cheyunkeji.er.utils.EncryptUtils;
import com.cheyunkeji.er.utils.PhoneUtil;
import com.cheyunkeji.er.utils.RxCaptcha;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.VerifyCodeView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

import static com.cheyunkeji.er.utils.RxCaptcha.TYPE.CHARS;

public class RegisterOrFindPsdActivity extends BaseActivity {

  private static final String REQUEST_MSG_VERIFY_CODE = "entry";

  private static final String REQUEST_RESET_PSD = "check";

  private static String captchaCode;

  @BindView(R.id.v_topbar)
  TopBar vTopbar;

  @BindView(R.id.et_phone_number)
  EditText etPhoneNumber;

  @BindView(R.id.et_tx_yzm)
  EditText etTxYzm;

  @BindView(R.id.iv_graphy_verify_code)
  ImageView ivGraphyVerifyCode;

  @BindView(R.id.ll_change_graphic_verify_code)
  LinearLayout llChangeGraphicVerifyCode;

  @BindView(R.id.et_msg_verify_code)
  EditText etMsgVerifyCode;

  @BindView(R.id.et_psd)
  EditText etPsd;

  @BindView(R.id.et_input_psd_again)
  EditText etInputPsdAgain;

  @BindView(R.id.et_realname)
  EditText etRealName;

  @BindView(R.id.btn_register)
  Button btnRegister;

  @BindView(R.id.activity_register)
  LinearLayout activityRegister;
  //    @BindView(R.id.ll_request_msg_code)
  //    LinearLayout llRequestMsgCode;
  @BindView(R.id.tv_send_verify_code)
  VerifyCodeView verifyCodeView;

  @BindView(R.id.tv_get_iv_code)
  TextView tvGetIvCode;

  private String TAG = RegisterOrFindPsdActivity.class.getSimpleName();
  //    当前意图 ： 注册 / 找回密码
  private int currentActionType = Constants.ACTION_REGISTER;
  private Bundle bundle;

  @Override
  protected void init() {
    setContentView(R.layout.activity_register);
    ButterKnife.bind(this);

    bundle = getIntent().getExtras();
    currentActionType = bundle.getInt(Constants.ENTRY_ACTION_TYPE);
  }

  @Override
  protected void initView() {

    if (currentActionType == Constants.ACTION_FIND_PSD_BACK) {
      vTopbar.setTitle("找回密码");
      if (!TextUtils.isEmpty(bundle.getString("phone_number")))
        etPhoneNumber.setText(bundle.getString("phone_number"));
      btnRegister.setText("确认提交");
      etPsd.setHint("设置新密码");
      etInputPsdAgain.setHint("再次输入新密码");
      etRealName.setVisibility(View.GONE);
    } else if (currentActionType == Constants.ACTION_REGISTER) {
      vTopbar.setTitle("注册");
      btnRegister.setText("注册");
    }

    vTopbar.setLeftBack();
    llChangeGraphicVerifyCode.setOnClickListener(this);
    btnRegister.setOnClickListener(this);
    verifyCodeView.setOnClickListener(this);
    etTxYzm.setFilters(
        new InputFilter[] {
          new InputFilter.LengthFilter(Constants.REGISTER_GRAPHIC_VERIFY_CODE_LENGTH),
          new AsciiCodeLimitFilter()
        });
    requestGraphicCode();
    etPhoneNumber.setOnFocusChangeListener(
        new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(View v, boolean hasFocus) {
            if (currentActionType == Constants.ACTION_FIND_PSD_BACK) {
              return;
            }
            if (!hasFocus && !TextUtils.isEmpty(etPhoneNumber.getText().toString())) {
              getRepeat(etPhoneNumber.getText().toString());
            }
          }
        });
    etInputPsdAgain.setOnFocusChangeListener(
        new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
              if (!TextUtils.equals(
                  etPsd.getText().toString(), etInputPsdAgain.getText().toString())) {
                SToast.show("密码不一致");
              }
            }
          }
        });
  }

  /**
   * 判断手机号码是否重复
   *
   * @param s
   */
  private void getRepeat(String s) {
    HashMap<String, String> params = new HashMap<>();
    params.put("mobile", s);

    ApiClient.postForm(
        HttpConstants.Repeat,
        params,
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {}

          @Override
          public void onResponse(String response, int id) {
            try {
              JSONObject obj = new JSONObject(response);
              if (obj.optInt("code") != 1) {
                SToast.show(obj.optString("msg"));
              }
            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
  }

  @Override
  protected void initData() {}

  @Override
  public void onClick(View v) {
    super.onClick(v);
    switch (v.getId()) {
      case R.id.ll_change_graphic_verify_code:
        if (TextUtils.isEmpty(etPhoneNumber.getText().toString())) {
          SToast.show("请输入手机号码");
          return;
        }
        if (PhoneUtil.isMobileNO(etPhoneNumber.getText().toString())) {
          requestGraphicCode();
        } else {
          SToast.show("手机号码格式有误");
        }
        break;
      case R.id.btn_register:
        if (TextUtils.isEmpty(etPhoneNumber.getText().toString())) {
          SToast.show("请输入手机号码");
          return;
        }
        if (!PhoneUtil.isMobileNO(etPhoneNumber.getText().toString())) {
          SToast.show("手机号码格式有误");
          return;
        }
        if (TextUtils.isEmpty(etMsgVerifyCode.getText().toString())) {
          SToast.show("请输入短信验证码");
          return;
        }
        if (TextUtils.isEmpty(etPsd.getText().toString())) {
          SToast.show("请设置密码");
          return;
        }

        if (TextUtils.isEmpty(etInputPsdAgain.getText().toString())) {
          SToast.show("请再次输入密码");
          return;
        }
        // 判断密码
        if (!Mijudge(etInputPsdAgain.getText().toString())) {
          SToast.show("密码长度不小于6位");
          return;
        }

        if (!TextUtils.equals(etPsd.getText().toString(), etInputPsdAgain.getText().toString())) {
          SToast.show("密码不一致");
          return;
        }
        if (currentActionType == Constants.ACTION_REGISTER
            && TextUtils.isEmpty(etRealName.getText().toString())) {
          SToast.show("请输入真实姓名");
          return;
        }
        if (currentActionType == Constants.ACTION_REGISTER) {
          registerAccount(
              etPhoneNumber.getText().toString(),
              etPsd.getText().toString(),
              etInputPsdAgain.getText().toString(),
              etMsgVerifyCode.getText().toString(),
              etRealName.getText().toString());
        } else {
          resetPsd(etPhoneNumber.getText().toString(), REQUEST_RESET_PSD);
        }
        break;
      case R.id.tv_send_verify_code:
        if (TextUtils.isEmpty(etPhoneNumber.getText().toString())) {
          SToast.show("请输入手机号码");
          return;
        }
        if (!PhoneUtil.isMobileNO(etPhoneNumber.getText().toString())) {
          SToast.show("手机号码格式有误");
          return;
        }
        //                if (TextUtils.isEmpty(etTxYzm.getText().toString())) {
        //                    SToast.show("请输入图形验证码");
        //                    return;
        //                }
        requestMsgVerifyCode(etPhoneNumber.getText().toString());
        //                if (verifyGraphicCodeIsRight(etTxYzm.getText().toString())) {
        //
        ////                    if (currentActionType == Constants.ACTION_REGISTER) {
        //                    requestMsgVerifyCode(etPhoneNumber.getText().toString());
        ////                    } else {
        ////                        resetPsd(etPhoneNumber.getText().toString(),
        // REQUEST_MSG_VERIFY_CODE);
        ////                    }
        //                }
        break;
      default:
        break;
    }
  }

  /**
   * 判断密码
   *
   * @param s
   * @return
   */
  private boolean Mijudge(String s) {
    //        String regExp = "w{6,}";
    //        Pattern p = Pattern.compile(regExp);
    //        Matcher m = p.matcher(s);
    //        return m.matches();
    return s.length() >= 6;
  }

  private void resetPsd(String phoneNumber, final String actionType) {

    HashMap<String, String> params = new HashMap<>();
    params.put("action", "check");
    params.put("mobile", phoneNumber);

    //        Log.e(TAG, "resetPsd: MD5 加密后密码 ： " +
    // EncryptUtils.encryptMD5ToString(etPsd.getText().toString().trim()) );

    //        if (TextUtils.equals(actionType, REQUEST_RESET_PSD)) {
    params.put("password", EncryptUtils.encryptMD5ToString(etPsd.getText().toString().trim()));
    params.put(
        "repass", EncryptUtils.encryptMD5ToString(etInputPsdAgain.getText().toString().trim()));
    params.put("code", etMsgVerifyCode.getText().toString().trim());
    //        }

    ApiClient.postForm(
        HttpConstants.RESET_PSD,
        params,
        new StringCallback() {

          @Override
          public void onError(Call call, Exception e, int id) {
            if (e instanceof UnknownHostException || e instanceof SocketException) {
              SToast.show(R.string.tip_network_error, Gravity.CENTER);
              return;
            }
          }

          @Override
          public void onResponse(String response, int id) {
            try {
              JSONObject obj = new JSONObject(response);
              if (obj.optInt("code") == 1) {

                //                        if (TextUtils.equals(actionType, REQUEST_MSG_VERIFY_CODE))
                // {
                //                            verifyCodeView.startCountDown();
                ////                            Log.e(TAG, "onResponse: " + obj.optString("data"));
                //
                //                        } else {
                SToast.show("修改成功");
                //                            Log.e(TAG, "onResponse: " + obj.optString("data"));
                MyApplication.getInstance().removeActivity(RegisterOrFindPsdActivity.class);
                //                        }

              } else {
                SToast.show(obj.optString("msg"));
              }

            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
  }

  /**
   * 注册账号
   *
   * @param phoneNumber
   * @param psd
   * @param ensurePsd
   * @param msgVerifyCode
   */
  private void registerAccount(
      String phoneNumber, String psd, String ensurePsd, String msgVerifyCode, String realName) {

    HashMap<String, String> params = new HashMap<>();
    params.put("mobile", phoneNumber);
    params.put("password", EncryptUtils.encryptMD5ToString(psd));
    params.put("repass", EncryptUtils.encryptMD5ToString(ensurePsd));
    params.put("realname", realName);
    params.put("code", msgVerifyCode);

    ApiClient.postForm(
        HttpConstants.USER_REGISTER,
        params,
        new StringCallback() {

          @Override
          public void onBefore(Request request, int id) {
            super.onBefore(request, id);
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            super.onAfter(id);
            dismissDialog();
          }

          @Override
          public void onError(Call call, Exception e, int id) {
            if (e instanceof UnknownHostException || e instanceof SocketException) {
              SToast.show(R.string.tip_network_error, Gravity.CENTER);
              return;
            }
          }

          @Override
          public void onResponse(String response, int id) {
            try {
              JSONObject jsonObject = new JSONObject(response);
              if (jsonObject.optInt("code", 0) == 1) {
                SToast.show("注册成功");
                MyApplication.getInstance().removeActivity(RegisterOrFindPsdActivity.class);
              } else {
                SToast.show(jsonObject.optString("msg"));
              }
            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
  }

  private boolean verifyGraphicCodeIsRight(String graphicCode) {

    if (!TextUtils.equals(graphicCode.toLowerCase(), captchaCode)) {
      SToast.show("图形验证码错误");
      return false;
    } else {
      return true;
    }
  }

  /**
   * 获取短信验证码
   *
   * @param phoneNumber
   */
  private void requestMsgVerifyCode(String phoneNumber) {

    HashMap<String, String> params = new HashMap<>();
    params.put("mobile", phoneNumber);
    String scene = "";
    if (currentActionType == Constants.ACTION_REGISTER) {
      scene = "register";
    } else if (currentActionType == Constants.ACTION_FIND_PSD_BACK) {
      scene = "forgot";
    }
    params.put("scenes", scene);
    String api = HttpConstants.REQUEST_MSG_VERIFY_CODE;
    //        if (currentActionType == Constants.ACTION_FIND_PSD_BACK) {
    //            api =    HttpConstants.RESET_PSD;
    //            params.put("action", "entry");
    //        }
    ApiClient.postForm(
        api,
        params,
        new StringCallback() {

          @Override
          public void onBefore(Request request, int id) {
            super.onBefore(request, id);
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            super.onAfter(id);
            dismissDialog();
          }

          @Override
          public void onError(Call call, Exception e, int id) {
            if (e instanceof UnknownHostException || e instanceof SocketException) {
              SToast.show(R.string.tip_network_error, Gravity.CENTER);
              return;
            }
          }

          @Override
          public void onResponse(String response, int id) {
            try {
              JSONObject jsonObject = new JSONObject(response);
              if (jsonObject.optInt("code", 0) == 1) {
                verifyCodeView.startCountDown();
              } else {
                SToast.show(jsonObject.optString("msg"));
              }

            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
  }

  /** 获取图形验证码 */
  private void requestGraphicCode() {
    RxCaptcha.build()
        .backColor(0xffffff)
        .codeLength(4)
        .fontSize(60)
        .lineNumber(0)
        .size(200, 70)
        .type(CHARS)
        .into(ivGraphyVerifyCode);
    captchaCode = RxCaptcha.build().getCode();
  }
}
